package com.xyzwps.ewa.modules.demo

import com.xyzwps.ewa.common.ServerException
import io.ktor.http.*
import io.ktor.server.routing.*

fun Route.demoAuth(build: Route.() -> Unit): Route {
    val demoRoute = createChild(DemoRouteSelector())
    demoRoute.build()
    return demoRoute
}

internal class DemoRouteSelector : RouteSelector() {
    override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation {
        val auth = context.call.request.queryParameters["auth"]
        if (auth.isNullOrBlank()) {
            return RouteSelectorEvaluation.Failure(
                RouteSelectorEvaluation.qualityFailedParameter,
                HttpStatusCode.Unauthorized
            )
        }

        if (auth == "throw") {
            throw ServerException("Demo Auth Failed", HttpStatusCode.Unauthorized)
        }

        return RouteSelectorEvaluation.Transparent
    }
}

